package com.jingantech.ngiam.cas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jingantech.ngiam.*;
import com.jingantech.ngiam.util.HttpClientUtil;
import com.jingantech.ngiam.util.StringUtil;
import com.jingantech.ngiam.util.XmlUtil;

import java.io.IOException;

/**
 * Created by fuzhong on 2017/1/9.
 */
public class CasService {

    /**
     * 同步验证接口,系统完成
     *
     * @param url 接口路径
     *            如：http://{ssoaddress}/ngiam-rst/cas/serviceValidate
     * @param ticket 登录时获得的ST信息
     * @param service 配置cas应用时配置的service参数,代表唯一的应用
     * @param format 返回数据的格式，可以是：json和xml
     * @return ResponseBody 账户信息
     * @throws IOException
     */
    public static ResponseBody casValidate (String url, String ticket, String service, Format format) throws IOException {
        RequestBody request = new RequestBody(url, ticket, service, format);
        check(request);
        String result = null;
        if(url.indexOf("https") > -1 || url.indexOf("HTTPS") > -1){
            result = HttpClientUtil.httpsGet(request.toString());
        }else{
            result = HttpClientUtil.httpGet(request.toString());
        }
        System.out.println(result);
        if (StringUtil.isEmpty(result)) {
            throw new CasResponseDataFormatException("response data is empty!");
        }
        switch (format){
            case json:
                return parseJSON(result);
            case xml:
                return parseXML(result);
            default:
                throw new CasRequestFailureException("request format is error!");
        }
    }

    /**
     * 验证requestBody
     *
     * @param requestBody
     */
    private static void check (RequestBody requestBody) {
        if (requestBody == null) {
            throw new CasRequestFailureException("request param is not null!");
        }
        if (StringUtil.isEmpty(requestBody.getUrl())) {
            throw new CasRequestFailureException("request url is not empty!");
        }
        if (StringUtil.isEmpty(requestBody.getService())) {
            throw new CasRequestFailureException("request service is not empty!");
        }
        if (StringUtil.isEmpty(requestBody.getTicket())) {
            throw new CasRequestFailureException("request ticket is not empty!");
        }
        if (requestBody.getFormat() == null) {
            throw new CasRequestFailureException("request format is not empty!");
        }
    }

    /**
     * 解析返回的json数据
     *
     * @param json 返回的json数据
     * @return
     */
    private static ResponseBody parseJSON (String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        if (!jsonObject.containsKey("serviceResponse")) {
            throw new CasResponseDataFormatException(json);
        }
        JSONObject jsonBody = jsonObject.getJSONObject("serviceResponse");
        if (jsonBody.containsKey("authenticationFailure")) {
            Object obj = jsonBody.get("authenticationFailure");
            if (obj instanceof String) {
                throw new CasRequestFailureException((String) obj);
            } else {
                JSONObject failure = jsonBody.getJSONObject("authenticationFailure");
                if (failure.containsKey("description")) {
                    throw new CasRequestFailureException(failure.getString("description"));
                } else {
                    throw new CasRequestFailureException(json);
                }
            }
        } else if (jsonBody.containsKey("authenticationSuccess")) {
            jsonBody = jsonBody.getJSONObject("authenticationSuccess");
            ResponseBody body = JSONObject.parseObject(jsonBody.toJSONString(), ResponseBody.class);
            return body;
        }
        throw new CasResponseDataFormatException(json);
    }

    /**
     * 解析返回的xml数据
     *
     * @param xml 返回的xml数据
     * @return
     */
    private static ResponseBody parseXML (String xml) {
        String json = XmlUtil.xml2JsonString(xml);
        return parseJSON(json);
    }

    /*
    public static void main(String[] args) throws IOException {
        String url = "http://localhost:8080/ngiam-rst/cas/serviceValidate";
        String ticket = "ST-e9c7002a-8b3a-480d-8de3-9475c063d24d";
        String service = "third-party-sso";
        ResponseBody body = CasService.casValidate(url, ticket, service, Format.json);
        System.out.println(body.getUser());
        System.out.println(body.getAttributes().get("userApiKey"));
        System.out.println(body.getAttributes().get("userId"));
    }
    */
}
